//
//  DMLoginModel.swift
//  DM_新浪微博
//
//  Created by Damon.JiAo on 16/2/26.
//  Copyright © 2016年 Demon_JiAo. All rights reserved.
//

import UIKit

class DMLoginModel: NSObject ,NSCoding{

    var access_token:String?
    
    var expires_in:NSTimeInterval = 0
    
    var uid:String?
    
    var profile_image_url:String?
    
    var screen_name:String?
    
    init(dic:[String:NSObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    /** 防止KVC时候发生崩溃 */
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    /** 保存 */
    func save(file:String){
        
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        let filePath = (path as NSString).stringByAppendingPathComponent(file)
        
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    
    /** 沙盒读取数据 */
    class func readObject(file:String) ->DMLoginModel? {
        
        /** 取得路径 -- 沙盒中的Document文件夹里面 */
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask,true).last!
        let filepath = (path as NSString).stringByAppendingPathComponent(file)
        
        return NSKeyedUnarchiver.unarchiveObjectWithFile(filepath) as? DMLoginModel
        
        
    }
    
    /** 归档 -- 保存到沙盒文件里面 */
    func encodeWithCoder(aCoder:NSCoder){
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(profile_image_url, forKey: "profile_image_url")

    }
    
    /** 接档 -> 沙盒里面二进制转化为对象 这是NSCodeing协议里面必须要实现的功能 */
    required init?(coder aDecoder: NSCoder) {
        
        self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
        
        self.expires_in = aDecoder.decodeObjectForKey("expires_in") as! NSTimeInterval
        
        self.uid  = aDecoder.decodeObjectForKey("uid") as? String
        
        self.screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        
        self.profile_image_url  = aDecoder.decodeObjectForKey("profile_image_url") as? String
    }
    
}
